import base64

import grpc
import lite_pb2_grpc as pb2_grpc
import lite_pb2 as pb2
import json

class LiteClient(object):
    """
    Client for gRPC functionality
    """

    def __init__(self):
        self.host = '192.168.2.182'
        self.server_port = 10999

        # instantiate a channel
        self.channel = grpc.insecure_channel(
            '{}:{}'.format(self.host, self.server_port))

        # bind the client and the server
        self.stub = pb2_grpc.TestProxyStub(self.channel)

    def read_clash_yaml_as_string(self,file_path):
        with open(file_path, 'r', encoding='utf-8') as file:
            clash_yaml_string = file.read()
            return clash_yaml_string

    def start_test(self):
        """
        Client function to call the rpc for StartTest
        """


        # 示例用法
        file_path = '../o/allnode.txt'
        clash_yaml_string = self.read_clash_yaml_as_string(file_path)
        if len(clash_yaml_string) < 10:
            print("未从节点列表获取节点信息无法进一步测试节点")
            return
        suburls = base64.b64decode(clash_yaml_string).decode('utf-8')
        nodes = suburls.split('\n')
        message = pb2.TestRequest(
            GroupName="?empty?",
            SpeedTestMode=pb2.SpeedTestMode.speedonly,
            PingMethod=pb2.PingMethod.googleping,
            SortMethod=pb2.SortMethod.rspeed,
            Concurrency=12,
            TestMode=8,
            Subscription=suburls,
            Language="en",
            FontSize=24,
            Theme="rainbow",
            Timeout=10,
            OutputMode=3
            )
        #print(f'{message}')
        #print(f'{message}')
        for response in self.stub.StartTest(message):

            print(f'{response }')
            print(f"获取的ID： {getattr(response, 'Id', None)}")
            print(f"获取的ID： {getattr(response, 'Id', None)}")
            print(f"获取的ID： {getattr(response, 'Id', None)}")
            print(f"获取的ID： {getattr(response, 'Id', None)}")

if __name__ == '__main__':
    client = LiteClient()
    client.start_test()
  